package top.lyc829.iot_server.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import top.lyc829.iot_server.bean.AccessLog;
import top.lyc829.iot_server.bean.User;
import top.lyc829.iot_server.dao.AccessLogDao;
import top.lyc829.iot_server.service.AccessLogService;
import top.lyc829.iot_server.service.UserService;

import java.util.Date;
import java.util.List;

@Service
public class AccessLogServiceImpl implements AccessLogService {

    @Autowired
    private AccessLogDao accessLogDao;

    @Autowired
    private UserService userService;

    @Override
    public List<AccessLog> findAccessLogs(int page) {
        if (page < 1) {
            return null;
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page - 1, 10, sort);
        List<AccessLog> accessLogs = accessLogDao.findAll(pageable).getContent();
        for (AccessLog accessLog : accessLogs) {
            User user = userService.findUserById(accessLog.getUserId());
            accessLog.setUsername((user == null || user.getName() == null || user.getName().isEmpty() ) ? "未知" : user.getName());
        }

        return accessLogs;
    }

    @Override
    public void add(Integer userId, Integer type, String typeId, Integer state) {
        AccessLog accessLog = new AccessLog();
        accessLog.setUserId(userId);
        accessLog.setType(type);
        accessLog.setTypeId(typeId);
        accessLog.setState(state);
        accessLog.setTime(new Date());
        accessLogDao.save(accessLog);
    }
}
